//
//  LKMyUpdateCustomerViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/5/10.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKMyUpdateCustomerViewController.h"
#import "LKMyContinuInvestFillCell.h"
#import "LKWriteContinuInvestCell.h"
#import "LKMyDescriptionCell.h"
#import "LKMyChooseCustomerViewController.h"
#import "LKMyChooseWorkerViewController.h"
#import "LKMyWorkerCheckViewController.h"
#import "LKCustomerModel.h"
#import "LKMyCommitApplyViewController.h"
@interface LKMyUpdateCustomerViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)LKBaseTableview *tableView;
@property(nonatomic,strong)NSArray *titlesArray;
@property(nonatomic,strong)NSMutableArray *customerArray;
@property(nonatomic,copy)NSString *fenzongStr;
@property(nonatomic,copy)NSString *owenerId;
@property(nonatomic,copy)NSString *changeRemark;
@property(nonatomic,strong)NSMutableArray *idsArray;
@property(nonatomic,copy)NSString *approveId;

@end

@implementation LKMyUpdateCustomerViewController
-(LKBaseTableview *)tableView{
    if (!_tableView) {
        _tableView = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, 12 + NAVIGATION_BAR_HEIGHT, WIDTH, HEIGHT - (NAVIGATION_BAR_HEIGHT + 12)) style:UITableViewStyleGrouped registercellClasss:@[@"LKMyContinuInvestFillCell",@"LKWriteContinuInvestCell",@"LKMyDescriptionCell"]];
        [self.view addSubview:_tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getChecker];
    self.tableView.estimatedRowHeight = 200;
    // Do any additional setup after loading the view.
}
-(void)setNavgationBackBtn{
    WS(weakSelf);
    [super setNavgationBackBtn];
    self.navigationItem.title = @"客户归属变更";
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn setTitleColor:blueDefault forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(commitCustomerOwnerUpdateAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}

/**
 提交客户归属变更

 */
-(void)commitCustomerOwnerUpdateAction:(UIButton *)btn{

    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:self.owenerId,@"OwnerId",self.changeRemark,@"ChangeRemark",self.idsArray,@"CustomerIds",self.approveId,@"Approval", nil];
    NSString *conveStr = [NSString convertToJsonData:param];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:commitCustomerOwnerUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        [SVProgressHUD showInfoWithStatus:@"变更请求成功"];
        UIViewController *vc = self.presentingViewController;
        while (vc.presentingViewController) {
            vc = vc.presentingViewController;
        }
        [vc dismissViewControllerAnimated:YES completion:nil];
//        [self.navigationController popViewControllerAnimated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"RealoadChangeSuccessNotice" object:nil];
    } failure:^(NSString * _Nullable errorMessage) {
        [SVProgressHUD showInfoWithStatus:errorMessage];
    }];
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf)
    if (indexPath.section == 0 || indexPath.section == 1) {
        LKWriteContinuInvestCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKWriteContinuInvestCell"];
        cell.contentLabel.textColor = blueDefault;
        cell.titleLabel.text = self.titlesArray[indexPath.section];
        return cell;
    }
    if (indexPath.section == 3) {
        LKMyDescriptionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMyDescriptionCell"];
        [[cell.textView rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
            weakSelf.changeRemark = x;
        }];
        return cell;
    }
    LKMyContinuInvestFillCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMyContinuInvestFillCell"];
    cell.titleLabel.text = self.titlesArray[indexPath.section];
    cell.contentTF.enabled = NO;
    cell.contentTF.text = self.fenzongStr;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return indexPath.section == 3 ? 226 : 43;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0000000000001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 12;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = cellHeaderBgColor;
    return view;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf)
    switch (indexPath.section) {
        case 0:
            {
                LKMyChooseCustomerViewController *vc = [[LKMyChooseCustomerViewController alloc] init];
                vc.customersBlcok = ^(NSArray *arr) {
                    weakSelf.customerArray = (NSMutableArray *)arr;
                    LKWriteContinuInvestCell *cell = (LKWriteContinuInvestCell *)[tableView cellForRowAtIndexPath:indexPath];
                    NSString *nameStr = @"";
                    for (NSInteger i = 0; i < weakSelf.customerArray.count; i++) {
                        LKCustomerModel *model = weakSelf.customerArray[i];
                        nameStr = [nameStr stringByAppendingString:[NSString stringWithFormat:@" %@",model.customerName]];
                        [weakSelf.idsArray addObject:model.customerId];
                    }
                    cell.contentLabel.text = nameStr;
                };
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        case 1:
        {
            LKMyChooseWorkerViewController *vc = [[LKMyChooseWorkerViewController alloc] init];
            LKWriteContinuInvestCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            vc.workerBlock = ^(LKYewuyuanModel *yewuyuanModel) {
                cell.contentLabel.text = yewuyuanModel.name;
                weakSelf.owenerId = yewuyuanModel.Id;
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;

        default:
            break;
    }

}

/**
 获取审批人员信息
 */
-(void)getChecker{
    WS(weakSelf)
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:getFenzongUrl header:[LKUserInforTool header] parameters:nil progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        self.fenzongStr = responseObject[@"result"][@"leaderName"];
        LKMyContinuInvestFillCell *cell = (LKMyContinuInvestFillCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
        cell.contentTF.text = self.fenzongStr;
        self.approveId = responseObject[@"result"][@"leaderId"];
    } failure:^(NSString * _Nullable errorMessage) {
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0/*延迟执行时间*/ * NSEC_PER_SEC));
        
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        });
        
        
    }];
}
-(NSArray *)titlesArray{
    if (!_titlesArray) {
        _titlesArray = @[@"选择客户",@"选择新客户经理",@"审批人员"];
    }
    return _titlesArray;
}
-(NSMutableArray *)customerArray{
    if (!_customerArray) {
        _customerArray = [[NSMutableArray alloc] init];
    }
    return _customerArray;
}
-(NSMutableArray *)idsArray{
    if (!_idsArray) {
        _idsArray = [[NSMutableArray alloc] init];
    }
    return _idsArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
